import paho.mqtt.client as mqtt
import json
from flask_socketio import SocketIO
from stationpilot.servers.common.shared import mqtt_subscriptions
import threading
# MQTT 配置
MQTT_BROKER = "localhost"
MQTT_PORT = 1883


# 初始化 MQTT 客户端

class apiServerMQTTClient():
    def __init__(self,sio = None):
        self.mqtt_client = mqtt.Client()
        self.socketio = sio
        self.setup_mqtt_client()
        self.connect2mqtt()
        self.start_mqtt_daemon()

    def set_socketio_instance(self,sio: SocketIO):
        """允许在外部注入 socketio 实例"""
        self.socketio = sio


    def on_mqtt_message(self,client, userdata, msg):
        """收到 MQTT 消息时转发到对应的 WS 客户端"""
        topic = msg.topic
        payload = msg.payload.decode()

        try:
            data = json.loads(payload)
        except Exception:
            data = {"raw": payload}

        if topic in mqtt_subscriptions and self.socketio:
            for sid in list(mqtt_subscriptions[topic]):
                self.socketio.emit("mqtt:message", {
                    "topic": topic,
                    "data": data
                }, namespace="/ws", to=sid)

    def setup_mqtt_client(self):
        self.mqtt_client.on_message = self.on_mqtt_message
    
    def connect2mqtt(self,):
        self.mqtt_client.connect(MQTT_BROKER, MQTT_PORT, 60)

    def start_mqtt_daemon(self,):
        self.mqtt_client.loop_forever()

    def get_mqtt_instance(self):
        return self.mqtt_client